package net.cloudcodex.client.storyboard.handler;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import net.cloudcodex.client.storyboard.cdo.CharacterKeyCDO;
import net.cloudcodex.client.storyboard.player.PlayerBoardEventBus;
import net.cloudcodex.shared.dto.msg.SceneDTO;
import net.cloudcodex.shared.rpc.CampaignRPC;
import net.cloudcodex.shared.rpc.CampaignRPCAsync;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.EventHandler;
import com.mvp4g.client.event.BaseEventHandler;

/**
 * Client-side cache of MessageDTO.
 * 
 * Deals with server-side service {@link CampaignRPC#getMessages}.
 * 
 * @author ADaroussin
 */
@EventHandler
public class SceneEventHandler extends BaseEventHandler<PlayerBoardEventBus> {
	protected final CampaignRPCAsync service;

	protected final SortedMap<CharacterKeyCDO, SceneTimer> sceneTimers = new TreeMap<CharacterKeyCDO, SceneTimer>();

	@Inject
	public SceneEventHandler(CampaignRPCAsync service) {
		this.service = service;
	}

	public void onRegisterToScene(long campaignId, long characterId, AsyncCallback<List<SceneDTO>> callback) {
		final CharacterKeyCDO characterKey = new CharacterKeyCDO(campaignId, characterId);
		// Creation of the SceneTimer, calls the server-side service in the row
		sceneTimers.put(characterKey, new SceneTimer(service, campaignId, characterId, callback));
	}

	public void onCheckScene(long campaignId, long characterId) {
		final CharacterKeyCDO characterKey = new CharacterKeyCDO(campaignId, characterId);
		final SceneTimer sceneTimer = sceneTimers.get(characterKey);
		sceneTimer.reset();
	}
	
	public void onUnregisterToScene(long campaignId, long characterId) {
		final CharacterKeyCDO characterKey = new CharacterKeyCDO(campaignId, characterId);
		final SceneTimer sceneTimer = sceneTimers.remove(characterKey);
		sceneTimer.stop();
	}
}
